import { getFaultByType, getFaultOptions, saveFault } from '@/api/knowledge'
import { ref } from 'vue'

/**
 * 获取故障库下拉选项
 */
export const useGetFaultOptions = () => {
  // 获取选项加载
  const loading = ref(false)

  // 获取选项请求参数
  const getOptionsParam = ref({
    limit: 50,
    page: 1,
    name: '',
  })

  // 下拉选项
  const options = ref<Array<FaultOption>>([])

  /**
   * 获取选项
   */
  const getOptions = async () => {
    loading.value = true
    const res = await getFaultOptions(getOptionsParam.value)
    loading.value = false
    options.value = res.data.data.rows
  }

  return {
    options,
    loading,
    getOptionsParam,
    getOptions,
  }
}

/**
 * 根据处理类型获取故障库
 */
export const useGetFaultByType = () => {
  // 获取故障库加载
  const loading = ref(false)

  // 获取故障库请求参数
  const getFaultParams = ref<Array<KnownAPIRequest.GetFaultByType>>([])

  // 故障库列表
  const faultList = ref<Array<FaultByType>>([])

  /**
   * 获取故障库
   */
  const getFault = async () => {
    loading.value = true
    const res = await getFaultByType(getFaultParams.value)
    faultList.value = res.data.data.rows
    loading.value = false
  }

  return {
    loading,
    faultList,
    getFaultParams,
    getFault,
  }
}

/**
 * 创建故障库
 */
export const useFaultCreate = () => {
  // 故障添加加载
  const createLoading = ref(false)

  // 故障表单
  const form = ref<KnownAPIRequest.KnownFaultAdd>({
    code: '',
    faultImages: [],
    faultReasons: [
      {
        id: '',
        content: '',
      },
    ],
    faultReasonCode: '',
    id: '',
    mobileShow: true,
    name: '',
    oneFaultTypeId: '',
    reportAnalysis: true,
    solutions: [
      {
        id: '',
        content: '',
      },
    ],
    solutionCode: '',
    solutionImages: [],
    status: false,
    threeFaultTypeId: '',
    twoFaultTypeId: '',
    visibilityType: 1,
    goodsTypeVos: [],
    delFaultReasonIds: [],
    delSolutionIds: [],
  })

  /**
   * 重置表单
   */
  const resetForm = () => {
    form.value = {
      code: '',
      faultImages: [],
      faultReasons: [
        {
          id: '',
          content: '',
        },
      ],
      faultReasonCode: '',
      id: '',
      mobileShow: true,
      name: '',
      oneFaultTypeId: '',
      reportAnalysis: true,
      solutions: [
        {
          id: '',
          content: '',
        },
      ],
      solutionCode: '',
      solutionImages: [],
      status: false,
      threeFaultTypeId: '',
      twoFaultTypeId: '',
      visibilityType: 1,
      goodsTypeVos: [],
      delFaultReasonIds: [],
      delSolutionIds: [],
    }
  }

  /**
   * 故障添加
   */
  const create = async () => {
    createLoading.value = true
    const res = await saveFault(form.value)
    createLoading.value = false
    return res.data
  }

  return {
    form,
    createLoading,
    create,
    resetForm,
  }
}
